import React, { useState, useEffect, useCallback } from 'react'
import { useParams, useNavigate } from 'react-router-dom'
import { usePapers } from '../hooks/usePapers'
import { ArxivPaper } from '../types/auth'
import { Button } from '../components/ui/Button'
import { Badge } from '../components/ui/Badge'
import { LoadingScreen } from '../components/ui/LoadingScreen'
import { 
  ArrowLeft,
  ExternalLink,
  Bookmark,
  BookmarkCheck,
  Share2,
  Download,
  Star,
  Calendar,
  User,
  Tag,
  Eye
} from 'lucide-react'
import { formatDistanceToNow } from 'date-fns'
import { cn } from '../utils/cn'

export function PaperDetail() {
  const { arxivId } = useParams<{ arxivId: string }>()
  const navigate = useNavigate()
  const { fetchPaper, bookmarkPaper, ratePaper } = usePapers()

  const [paper, setPaper] = useState<ArxivPaper | null>(null)
  const [loading, setLoading] = useState(true)
  const [isBookmarked, setIsBookmarked] = useState(false)
  const [rating, setRating] = useState(0)

  const loadPaper = useCallback(async () => {
    if (!arxivId) return

    setLoading(true)
    try {
      const paperData = await fetchPaper(arxivId)
      setPaper(paperData)
      
      // Simulate checking bookmark status
      setIsBookmarked(false) // This would come from API
      setRating(0) // This would come from API
    } catch (error) {
      console.error('Error loading paper:', error)
    } finally {
      setLoading(false)
    }
  }, [arxivId, fetchPaper])

  const trackPaperView = useCallback(() => {
    // Track that user viewed this paper
    console.log('Tracking paper view for:', arxivId)
  }, [arxivId])

  useEffect(() => {
    if (arxivId) {
      loadPaper()
      // Track paper view
      trackPaperView()
    }
  }, [arxivId, loadPaper, trackPaperView])

  const handleBookmark = async () => {
    if (!paper) return
    
    try {
      await bookmarkPaper(paper.id)
      setIsBookmarked(!isBookmarked)
    } catch (error) {
      console.error('Error bookmarking paper:', error)
    }
  }

  const handleRate = async (newRating: number) => {
    if (!paper) return
    
    try {
      await ratePaper(paper.id, newRating)
      setRating(newRating)
    } catch (error) {
      console.error('Error rating paper:', error)
    }
  }

  const handleShare = async () => {
    if (navigator.share && paper) {
      try {
        await navigator.share({
          title: paper.title,
          text: `Check out this paper: ${paper.title}`,
          url: window.location.href
        })
      } catch (error) {
        // Fallback to copying URL
        navigator.clipboard.writeText(window.location.href)
        alert('URL copied to clipboard!')
      }
    } else {
      // Fallback for browsers without Web Share API
      navigator.clipboard.writeText(window.location.href)
      alert('URL copied to clipboard!')
    }
  }

  const estimateReadingTime = (text: string) => {
    const wordsPerMinute = 200
    const wordCount = text.split(' ').length
    return Math.ceil(wordCount / wordsPerMinute)
  }

  if (loading) {
    return <LoadingScreen />
  }

  if (!paper) {
    return (
      <div className="text-center py-12">
        <h2 className="text-2xl font-bold text-gray-900 mb-2">Paper Not Found</h2>
        <p className="text-gray-600 mb-6">
          The paper you're looking for could not be found.
        </p>
        <Button onClick={() => navigate('/app/browse')}>
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back to Browse
        </Button>
      </div>
    )
  }

  return (
    <div className="max-w-4xl mx-auto">
      {/* Header */}
      <div className="mb-6">
        <Button 
          variant="ghost" 
          onClick={() => navigate(-1)}
          className="mb-4"
        >
          <ArrowLeft className="mr-2 h-4 w-4" />
          Back
        </Button>
        
        <div className="bg-white rounded-lg border border-gray-200 p-6">
          {/* Paper metadata */}
          <div className="flex items-center space-x-4 text-sm text-gray-600 mb-4">
            <span className="flex items-center">
              <Calendar className="h-4 w-4 mr-1" />
              Published {formatDistanceToNow(new Date(paper.published_date), { addSuffix: true })}
            </span>
            <span>arXiv:{paper.arxiv_id}</span>
            <span className="flex items-center">
              <Eye className="h-4 w-4 mr-1" />
              {Math.floor(Math.random() * 1000)} views
            </span>
            <span>{estimateReadingTime(paper.abstract)} min read</span>
          </div>

          {/* Title */}
          <h1 className="text-3xl font-bold text-gray-900 mb-4 leading-tight">
            {paper.title}
          </h1>

          {/* Authors */}
          <div className="flex items-center mb-4">
            <User className="h-4 w-4 text-gray-400 mr-2" />
            <div className="flex flex-wrap gap-2">
              {paper.authors.map(author => (
                <button
                  key={author}
                  onClick={() => navigate(`/app/browse?author=${encodeURIComponent(author)}`)}
                  className="text-blue-600 hover:text-blue-800 hover:underline"
                >
                  {author}
                </button>
              ))}
            </div>
          </div>

          {/* Categories */}
          <div className="flex items-center mb-6">
            <Tag className="h-4 w-4 text-gray-400 mr-2" />
            <div className="flex flex-wrap gap-2">
              {paper.categories.map(category => (
                <Badge 
                  key={category} 
                  variant="secondary"
                  className="cursor-pointer hover:bg-gray-200"
                  onClick={() => navigate(`/app/browse?category=${category}`)}
                >
                  {category}
                </Badge>
              ))}
            </div>
          </div>

          {/* Actions */}
          <div className="flex flex-wrap items-center gap-3">
            <Button
              variant="outline"
              onClick={handleBookmark}
              className="flex items-center"
            >
              {isBookmarked ? (
                <BookmarkCheck className="h-4 w-4 mr-2 text-blue-600" />
              ) : (
                <Bookmark className="h-4 w-4 mr-2" />
              )}
              {isBookmarked ? 'Bookmarked' : 'Bookmark'}
            </Button>

            <Button
              variant="outline"
              onClick={() => window.open(paper.pdf_url, '_blank')}
              className="flex items-center"
            >
              <ExternalLink className="h-4 w-4 mr-2" />
              View PDF
            </Button>

            <Button
              variant="outline"
              onClick={handleShare}
              className="flex items-center"
            >
              <Share2 className="h-4 w-4 mr-2" />
              Share
            </Button>

            <Button
              variant="outline"
              onClick={() => window.open(paper.pdf_url, '_blank')}
              className="flex items-center"
            >
              <Download className="h-4 w-4 mr-2" />
              Download
            </Button>
          </div>
        </div>
      </div>

      {/* Content */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        {/* Main content */}
        <div className="lg:col-span-2 space-y-6">
          {/* Abstract */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">Abstract</h2>
            <p className="text-gray-700 leading-relaxed whitespace-pre-wrap">
              {paper.abstract}
            </p>
          </div>

          {/* Additional metadata */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h2 className="text-xl font-semibold text-gray-900 mb-4">Details</h2>
            
            <div className="space-y-3 text-sm">
              <div className="flex justify-between">
                <span className="text-gray-600">Submitted:</span>
                <span className="text-gray-900">
                  {new Date(paper.published_date).toLocaleDateString()}
                </span>
              </div>
              
              {paper.updated_date !== paper.published_date && (
                <div className="flex justify-between">
                  <span className="text-gray-600">Last updated:</span>
                  <span className="text-gray-900">
                    {new Date(paper.updated_date).toLocaleDateString()}
                  </span>
                </div>
              )}
              
              {paper.doi && (
                <div className="flex justify-between">
                  <span className="text-gray-600">DOI:</span>
                  <a 
                    href={`https://doi.org/${paper.doi}`}
                    target="_blank"
                    rel="noopener noreferrer"
                    className="text-blue-600 hover:text-blue-800 hover:underline"
                  >
                    {paper.doi}
                  </a>
                </div>
              )}
              
              {paper.journal_reference && (
                <div className="flex justify-between">
                  <span className="text-gray-600">Journal:</span>
                  <span className="text-gray-900">{paper.journal_reference}</span>
                </div>
              )}
            </div>
          </div>
        </div>

        {/* Sidebar */}
        <div className="space-y-6">
          {/* Rating */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-900 mb-4">Rate This Paper</h3>
            
            <div className="flex items-center justify-center space-x-1 mb-4">
              {[1, 2, 3, 4, 5].map((star) => (
                <button
                  key={star}
                  onClick={() => handleRate(star)}
                  className="p-1 hover:bg-gray-100 rounded transition-colors"
                >
                  <Star
                    className={cn(
                      "h-6 w-6 transition-colors",
                      star <= rating 
                        ? "text-yellow-400 fill-current" 
                        : "text-gray-300 hover:text-yellow-400"
                    )}
                  />
                </button>
              ))}
            </div>
            
            <p className="text-sm text-gray-600 text-center">
              {rating > 0 
                ? `You rated this paper ${rating} star${rating > 1 ? 's' : ''}`
                : 'Click stars to rate this paper'
              }
            </p>
          </div>

          {/* Quick actions */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-900 mb-4">Quick Actions</h3>
            
            <div className="space-y-3">
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start"
                onClick={() => navigate(`/app/browse?author=${encodeURIComponent(paper.authors[0])}`)}
              >
                <User className="h-4 w-4 mr-3" />
                More from {paper.authors[0].split(' ').slice(-1)[0]}
              </Button>
              
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start"
                onClick={() => navigate(`/app/browse?category=${paper.categories[0]}`)}
              >
                <Tag className="h-4 w-4 mr-3" />
                Browse {paper.categories[0]}
              </Button>
              
              <Button
                variant="ghost"
                size="sm"
                className="w-full justify-start"
                onClick={() => navigate('/app/library')}
              >
                <Bookmark className="h-4 w-4 mr-3" />
                View My Library
              </Button>
            </div>
          </div>

          {/* Related papers placeholder */}
          <div className="bg-white rounded-lg border border-gray-200 p-6">
            <h3 className="font-semibold text-gray-900 mb-4">Related Papers</h3>
            <p className="text-sm text-gray-600">
              Related paper recommendations will appear here based on your reading history and preferences.
            </p>
          </div>
        </div>
      </div>
    </div>
  )
}